package com.md5;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Util {
	
	private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	private static MessageDigest getAlgorithm(String algorithm){
		MessageDigest instance=null;
		try {
			instance = MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return instance;
	}	
	public static String encode(String algorithm,String encodeStr){
		byte []bytes=getAlgorithm(algorithm).digest(encodeStr.getBytes());
		return toHexString(bytes);
	}
	private static String toHexString(byte[] bytes){	
		StringBuffer str=new StringBuffer();
		for(Byte b:bytes){			
			str.append( hexDigits[b>>4 & 0xf]);
			str.append( hexDigits[b &0xf ]);
		}
		//System.out.println("str="+str+","+str.length());
		return str.toString();
	}
	public static void main(String[] args) throws UnsupportedEncodingException {		
	}
}
